package com.lerays.spider.sougou;

import org.lionsoul.websnail.Spider;
import org.lionsoul.websnail.SpiderListener;

import com.lerays.spider.sougou.handler.ListenerCallbackHandler;

/**
 * wechat spider listener
 * 
 * @author chenxin<chenxin619315@gmail.com>
 */
public class SougouSpiderListener implements SpiderListener
{
	private SougouSpider wechatSpider = null;
	
	public SougouSpiderListener( SougouSpider wechatSpider )
	{
		this.setWechatSpider(wechatSpider);
	}
	
	@Override
	public void onStartup(Spider spider) 
	{
		
	}

	@Override
	public void onPause(Spider spider) 
	{
		//check and invoke the callback
		if ( wechatSpider.getTaskAccomplishHook() != null )
		{
			String status = "pause-api";
			if ( wechatSpider.getLastErrorMsg() != null 
					&& ( (wechatSpider.getSpider().getTodoHandler().size() + 10) 
							<= wechatSpider.getSourceSize() ) )
			{
				status = "pause-expired";
			}
			
			new Thread(new ListenerCallbackHandler(
					wechatSpider,
					wechatSpider.getTaskAccomplishHook(),
					status
			)).start();
		}
		
		System.out.println("@Websnail#: Spider paused!");
	}

	@Override
	public void onResume(Spider spider) 
	{
		System.out.println("@Websnail#: Spider resumed!");
	}

	@Override
	public void onAccomplish(Spider spider) 
	{
		spider.pause();
		
		//make sure the spider has ever started
		if ( wechatSpider.getLastStartTime() <= 0 )
		{
			return;
		}
		
		//update the recent end time
		wechatSpider.setRecentEndTime(System.currentTimeMillis() / 1000);
		
		//check and invoke the callback
		if ( wechatSpider.getTaskAccomplishHook() != null )
		{
			new Thread(new ListenerCallbackHandler(
					wechatSpider,
					wechatSpider.getTaskAccomplishHook(),
					"accomplish"
			)).start();
		}
	}

	@Override
	public void onShutdown(Spider spider) 
	{
		
	}

	public SougouSpider getWechatSpider() 
	{
		return wechatSpider;
	}

	public void setWechatSpider(SougouSpider wechatSpider) 
	{
		this.wechatSpider = wechatSpider;
	}

}
